<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\{Seckill as SeckillModel,SeckillDetail};

class Seckill extends Base{
    

    /**
     * 首页
     */
    public function index(){
        if(IS_POST) {
            $search  = request()->param();
            $where = [];
            if(isset($search["title"]) && $search["title"]!="") $where[] = ["title","=",$search["title"]];

            $db   = SeckillModel::where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            $redis = redis_instance();
             if(count($list)){
                foreach($list as &$v){
                    $v["goods_thumb"] = table_img($v["goods_thumb"]);
                    $v['start_time'] = date('Y-m-d H:i:s',$v['start_time']);
                    $v['end_time'] = date('Y-m-d H:i:s',$v['end_time']);
                    $v['is_show'] = table_switch('Seckill/is_show', ['id'=>$v['id']], $v['is_show'] == 1 ? true : false,'是|否');
                    $v['redis_stock'] = $redis->lLen("{$this->redis_key}:SeckillStock:{$v['id']}");
                }
            }

            admin_response(0, 'success', $list, $db->count());
        }
        if(IS_EXCEL) {
            $db = SeckillModel::where($where)->order('id asc');
            big_array_to_csv($db, '数据导出', []);
        }
        return $this->render_table([
           "page"=>true,
            "toolbar" => [table_button('admin/Seckill/add',"添加","frame",'',['850px','600px'])],
            "toolbar_row" => [ 
                    table_button('admin/Seckill/edit',"编辑","frame",'',['850px','600px']),
                    table_button('admin/Seckill/add_stock',"添加库存","frame",'',['850px','600px']),
                    table_button('admin/Seckill/del',"删除","confirm")
                    ],
            "cols" => [ 
                     ["type"=>"checkbox"],
                    ["field"=>"title", "title"=>"标题","align"=>"center"],
                    ["field"=>"start_time", "title"=>"开始时间","align"=>"center"],
                    ["field"=>"end_time", "title"=>"结束时间","align"=>"center"],
                    ["field"=>"goods_thumb", "title"=>"商品图片","align"=>"center"],
                    ["field"=>"goods_price", "title"=>"商品原价","align"=>"center"],
                    ["field"=>"stock", "title"=>"秒杀库存","align"=>"center"],
                    ["field"=>"price", "title"=>"秒杀价格","align"=>"center"],
                    ["field"=>"redis_stock", "title"=>"剩余库存","align"=>"center"],
                    ["field"=>"is_show", "title"=>"是否显示","align"=>"center"]

            ],
            "where"=>[
                    "title"=>["type"=>"input","title"=>"标题"],

            ]

            ],false);

    }

        /**
     * 上架/下架操作
     * date 2021/3/17 11:20
     */
    public function is_show() {
        $id      = param_check('id');
        $checked = param_check('checked', 0);
        $res = SeckillModel::where('id', $id)->update([
            'is_show'        => $checked ? 1 : 0,
            'update_time'   => time()
        ]);
        $res ? json_response(1, '修改成功') : json_response(0, '修改失败');
    }

    /**
     * 添加库存
     * @return void
     * @author Sam
     * date 2021-12-03
     */
    public function add_stock() {
        $id = param_check('id');
        if(IS_POST) {
            $stock = param_check('stock');
            $detail = SeckillModel::find($id);
            $detail->stock += $stock;
            $res = $detail->save();
            if($res){
                $redis = redis_instance();
                $redis->multi(\Redis::PIPELINE);
                for($i=1; $i<=$stock; $i++) {
                    $redis->lPush("{$this->redis_key}:SeckillStock:{$id}", 1);
                }
                $redis->exec();
                json_response(1, '添加库存成功');
            }else{
                json_response(0, '添加库存失败');
            }
            }
        return $this->render_form([
            ['type'=>'text', 'name'=>'stock', 'title'=>'添加库存', 'text_type'=>'number', 'remark'=>'请输入添加库存数量']
        ]);
    }

        /**
     * 添加
     * @return void
     * @author 
     * date 
     */
    public function add(){
        if(request()->isPost()) {
           $data = request()->post();
           if($data['goods_type'] == 2 && !$data['goods_id']) json_response(0,'请选择商品');
            $data['start_time'] = strtotime($data['start_time']);
             $data['end_time'] = strtotime($data['end_time']);
             if(strtotime($data['end_time']) < strtotime($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if($res = SeckillModel::create($data)){
                if(!empty($data['stock'])) {
                    $redis = redis_instance();
                    $redis->multi(\Redis::PIPELINE);
                    for($i=1; $i<=$data['stock']; $i++) {
                        $redis->lPush("{$this->redis_key}:SeckillStock:{$res->id}", 1);
                    }
                    $redis->exec();
                }
                json_response(1,'操作成功');
           } 
           json_response(0,'操作失败');
        }else{
            $db_pre = app()->env->get(SYSTEM.'.db_pre');
            $exits = Db::query('show tables like "'.$db_pre.'goods"');
            $option = [];
            if(count($exits)){
                $option = Db::name('goods')->field('id as value,title')->select();
            }
           return $this->render_form([
                    ["type"=>"text","name"=>"title","title"=>"标题","lay-verify"=>"required"],
                    ["type"=>"textarea","name"=>"sub_title","title"=>"简介","lay-verify"=>"required"],
                    [
                        ["type"=>"text","text_type"=>"datetime","name"=>"start_time","title"=>"开始时间","lay-verify"=>"required",'readonly'=>true],
                        ["type"=>"text","text_type"=>"datetime","name"=>"end_time","title"=>"结束时间","lay-verify"=>"required",'readonly'=>true],
                    ],
                    
                    ["type"=>"radio","name"=>"goods_type","title"=>"商品类型","lay-verify"=>"required","option"=>[["value"=>1,"title"=>"自定义"],["value"=>2,"title"=>"商品库"]]],
                    ["type"=>"upload","name"=>"goods_thumb","title"=>"商品图片","lay-verify"=>"required"],
                    ["type"=>"select","name"=>"goods_id","title"=>"商品选择（商品库必选）",'option'=>$option],
                    [
                        ["type"=>"text","name"=>"goods_price","title"=>"商品原价","lay-verify"=>"required"],
                        ["type"=>"text","name"=>"stock","title"=>"秒杀库存","lay-verify"=>"required"],
                    ],
                     ["type"=>"text","name"=>"price","title"=>"秒杀价","lay-verify"=>"required"],
                    
                    ["type"=>"editor","name"=>"detail","title"=>"详情","lay-verify"=>"required"]
           ]);
        }
    }



    /**
     * 编辑
     * @return void
     * @author 
     * date 
     */
    public function edit(){
        $id = \param_check('id');
        if(request()->isPost()) {
           $data = request()->post();
           $SeckillModel = SeckillModel::find($id);
             if($data['goods_type'] == 2 && !$data['goods_id']) json_response(0,'请选择商品');
             $data['start_time'] = strtotime($data['start_time']);
             $data['end_time'] = strtotime($data['end_time']);
             if($SeckillModel->start_time <= time()){
                 //活动已经开始
                 unset($data['stock']);
                 unset($data['price']);
             }
             if(strtotime($data['end_time']) < strtotime($data['start_time'])) json_response(0,'结束时间不得早于开始开始');
           if(SeckillModel::update($data,['id'=>$id])) json_response(1,'操作成功');
           json_response(0,'操作失败');
        }else{
            $data = SeckillModel::find($id);
            $data['start_time'] = date('Y-m-d H:i:s',$data['start_time']);
             $data['end_time'] = date('Y-m-d H:i:s',$data['end_time']);
           return $this->render_form([
                ["type"=>"text","name"=>"title","title"=>"标题","lay-verify"=>"required"],
                ["type"=>"textarea","name"=>"sub_title","title"=>"简介","lay-verify"=>"required"],
                [
                    ["type"=>"text","text_type"=>"datetime","name"=>"start_time","title"=>"开始时间","lay-verify"=>"required",'readonly'=>true],
                    ["type"=>"text","text_type"=>"datetime","name"=>"end_time","title"=>"结束时间","lay-verify"=>"required",'readonly'=>true],
                ],
                
                ["type"=>"radio","name"=>"goods_type","title"=>"商品类型","lay-verify"=>"required","option"=>[["value"=>1,"title"=>"自定义"],["value"=>2,"title"=>"商品库"]]],
                ["type"=>"upload","name"=>"goods_thumb","title"=>"商品图片","lay-verify"=>"required"],
                ["type"=>"select","name"=>"goods_id","title"=>"商品选择（商品库必选）",'option'=>$option],
                [
                    ["type"=>"text","name"=>"goods_price","title"=>"商品原价","lay-verify"=>"required"],
                    ["type"=>"text","name"=>"stock","title"=>"秒杀库存","lay-verify"=>"required"],
                ],
                ["type"=>"text","name"=>"price","title"=>"秒杀价","lay-verify"=>"required"],
                
                ["type"=>"editor","name"=>"detail","title"=>"详情","lay-verify"=>"required"]

           ],$data);
        }
    }





        /**
     * 删除
     * @return void
     * @author Sam
     * date 2021-07-01
     */
    public function del(){
        $id = param_check('id');
        if(!$SeckillModel = SeckillModel::get($id)) json_response(0,'不存在');
        if($SeckillModel->delete()) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }



        /**
     * 砍价订单
     * @return [type] [description]
     */
    public function seckill_order(){
        $search  = request()->param();
        $where = [];
        if(!empty($search['aid'])) $where[] = ['aid', '=', $search['aid']];
        if(!empty($search['pay_status']) && $search['pay_status']!='') $where[] = ['pay_status', '=', $search['pay_status']];
        if(!empty($search['user']) && $search['user']!=''){
            $uid = UserModel::where('nickname|mobile','like',"%{$search['user']}%")->column('id');
            if(count($uid)) $where[] = ['uid','in',$uid];
        }
        if(IS_POST) {
            $db   = SeckillDetail::with(['user','activity'])->where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            foreach ($list as $key => $value) {
                if($value->pay_status == 0){
                    $pay_text = '待支付';
                }elseif($value->pay_status == 1){
                    $pay_text = '已支付';
                }elseif($value->pay_status == -1){
                    $pay_text = '已过期';
                }
                $value['pay_text'] = $pay_text;
            }
            admin_response(0, 'success', $list, $db->count());
        }

         $option = SeckillModel::field('id as value,title')->select();
        return $this->render_table([
            "page"=>true,
             "cols" => [ 
                      ["type"=>"checkbox"],
                      ["field"=>"order_sn", "title"=>"订单编号","align"=>"center"],
                     ["field"=>"title", "title"=>"活动","align"=>"center"],
                     ["field"=>"nickname", "title"=>"用户","align"=>"center"],
                     ["field"=>"mobile", "title"=>"用户手机","align"=>"center"],
                     ["field"=>"price", "title"=>"价格","align"=>"center"],
                     ["field"=>"pay_text", "title"=>"支付状态","align"=>"center"]
             ],
             "where"=>[
                 'user'  => ['type'=>'input', 'title'=>'用户','placeholder'=>'输入用户'],
                 'aid'  =>  ['type'=>'select', 'title'=>'活动','placeholder'=>'选择活动','option'=>$option],
                 'pay_status'  => ['type'=>'select', 'title'=>'支付状态','option'=>[
                    ['value'=>0,'title'=>'待支付'],
                    ['value'=>1,'title'=>'已支付'],
                    ['value'=>-1,'title'=>'已过期']
                ]],
             ]
 
             ],false);
    }


        /**
     * 砍价记录
     * @return void
     * @author Sam
     * date 2021-09-09
     */
    public function help_log(){
        $search  = request()->param();
        $where = [];
        if(!empty($search['aid'])) $where[] = ['aid', '=', $search['aid']];
        if(IS_POST) {
            $db   = BargainLog::with(['help_from','help_to','activity'])->where($where)->order('id desc');
            $list = $db->limit(paginator())->select();
            foreach ($list as $key => $value) {
                $value['from_mobile'] = substr(  $value['from_mobile'],0,4).'****'.substr(  $value['from_mobile'],7,11);
                $value['to_mobile'] = substr(  $value['to_mobile'],0,4).'****'.substr(  $value['to_mobile'],7,11);
            }
            admin_response(0, 'success', $list, $db->count());
        }
        if(IS_EXCEL) {
            $db = BargainLog::with(['help_from','help_to','activity'])->where($where)->order('id desc');
            big_array_to_csv($db, '助力记录', [
                'title'         => '活动',
                'from_nickname' => ['助力人昵称',function($row){
                    return iconv('gb2312//ignore', 'utf-8', iconv('utf-8', 'gb2312//ignore', $row['from_nickname']));
                }],
                'from_mobile'   => '助力人手机',
                'to_nickname'   => ['被助力人昵称',function($row){
                    return iconv('gb2312//ignore', 'utf-8', iconv('utf-8', 'gb2312//ignore', $row['to_nickname']));
                }],
                'to_mobile'     => '被助力人手机',
                'create_time'   => '助力时间',
                'bargain_price' => '砍掉价格',
                'create_time' => '助力时间'
            ]);
        }
        $option = SeckillModel::field('id as value,title')->select();
        return $this->render_table([
            "page"=>true,
            'export'=>true,
             "cols" => [ 
                      ["type"=>"checkbox"],
                     ["field"=>"title", "title"=>"活动","align"=>"center"],
                     ["field"=>"from_nickname", "title"=>"助力人昵称","align"=>"center"],
                     ["field"=>"from_mobile", "title"=>"助力人手机","align"=>"center"],
                     ["field"=>"to_nickname", "title"=>"被助力人昵称","align"=>"center"],
                     ["field"=>"to_mobile", "title"=>"被助力人手机","align"=>"center"],
                     ["field"=>"bargain_price", "title"=>"砍价金额","align"=>"center"],
                     ["field"=>"create_time", "title"=>"助力时间","align"=>"center"],
             ],
             "where"=>[
                 'aid'  => ['type'=>'select', 'title'=>'活动','placeholder'=>'选择活动','option'=>$option],
             ]
 
             ],false);
    }

}